package com.yuexiang.melodyhub.authserver.handler;

import com.yuexiang.melodyhub.authserver.feign.UserFeignService;
import com.yuexiang.melodyhub.authserver.handler.context.RegisterContext;
import com.yuexiang.melodyhub.common.constant.UsualConstant.BizCodeConstant;
import com.yuexiang.melodyhub.common.dto.user.UserFindByEmail.param.UserFindByEmailParam;
import com.yuexiang.melodyhub.common.dto.user.UserFindByEmail.response.UserFindByEmailResponse;
import com.yuexiang.melodyhub.common.exception.RequestArgumentException;
import com.yuexiang.melodyhub.common.exception.gateway.UnavailableServiceException;
import com.yuexiang.melodyhub.common.handler.AbstractValidationHandler;
import com.yuexiang.melodyhub.common.result.ResultData;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class EmailValidationHandler extends AbstractValidationHandler<RegisterContext> {

    @Autowired
    private UserFeignService userFeignService;

    @Override
    public void handler(RegisterContext content) {
        if (!EmailValidator.getInstance().isValid(content.getOAuthRegisterParam().getEmail()))
            throw new RequestArgumentException(BizCodeConstant.Msg.EMAIL_IS_INVALID);
        ResultData<UserFindByEmailResponse> userFindByEmailResponse;
        try {
            userFindByEmailResponse = userFeignService.findByEmail(new UserFindByEmailParam(content.getOAuthRegisterParam().getEmail()));
        } catch (Exception e) {
            throw new UnavailableServiceException();
        }
        if (userFindByEmailResponse.getData() != null)
            throw new RequestArgumentException(BizCodeConstant.Msg.U_IS_EXIST);
        handlerNext(content);
    }
}
